import React from 'react'
import { View, StyleSheet, Alert, BackHandler, PermissionsAndroid, Linking } from 'react-native'
import { WebView } from 'react-native-webview';
import Share from "react-native-share";
import geolocation from '@react-native-community/geolocation'
import NetInfo from '@react-native-community/netinfo'
import Marker from "react-native-image-marker"
// import Imp from 'react-native-image-picker';
import * as Imp from 'react-native-image-picker/src';



import ImagePicker from 'react-native-image-crop-picker';
import DeviceInfo from 'react-native-device-info';
import RNFS from 'react-native-fs';
import { AudioRecorder, AudioUtils } from 'react-native-audio'
import Sound from 'react-native-sound'
import * as imgp from './RecordVideView'
import queryString from 'query-string';
export default class HomeView extends React.Component {
    componentDidMount() {
        this.backHandle = BackHandler.addEventListener('hardwareBackPress', () => {
            if (this.refs.webview) {
                this.refs.webview.goBack();
                return true;
            }
            return false;
        });
        this.audioEvent();
        this.subscription = NetInfo.addEventListener(
            this.handleConnectivityChange,
        );
    }

    handleConnectivityChange = (state) => {
        let str = JSON.stringify(state);
        this.refs.webview.injectJavaScript(`netinfo(' ${str}');true;`);
    };
    componentWillUnmount() {
        if (this.backHandle) {
            this.backHandle.remove();
        }
        this.subscription && this.subscription();
    }

    render() {
        const patchPostMessageFunction = function () {
            let originalPostMessage = window.postMessage;
            let patchedPostMessage = function (message, targetOrigin, transfer) {
                originalPostMessage(message, targetOrigin, transfer);
            };
            patchedPostMessage.toString = function () {
                return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
            };
            window.postMessage = patchedPostMessage;
        };
        // {uri: 'http://192.168.137.154:8878/'}
        //{uri: 'file:///android_asset/www/index.html'}
        const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';
        return <View style={styles.container}>
            <WebView
                source={
                    { uri: 'file:///android_asset/www/index.html' }
                    // { uri: 'http://b35114658l.51vip.biz/www/index.html' }
                    // { uri: 'http://192.168.137.1:8080/www/index.html' }
                }
                ref={"webview"}
                originWhitelist={['*']}
                automaticallyAdjustContentInsets={false}
                androiddomStorageEnabled={false}
                injectedJavaScript={patchPostMessageJsCode}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                decelerationRate="normal"
                startInLoadingState={true}
                allowUniversalAccessFromFileURLs={true}
                allowFileAccess={true}
                onLoad={this.loadMap.bind(this)}
                onMessage={this.messageData.bind(this)}
                onError={this.loadError.bind(this)}
            />
        </View>
    }

    loadMap() {

    }

    messageData(event) {
        let data = event.nativeEvent.data;
        let obj = JSON.parse(data);
        switch (obj.type) {
            case 'takePhotos':
                this.takePhotos();
                break;
            case 'recordVideo':
                this.recordVideo()
                break;
            case 'startRecordAudio':
                this.startRecordAudio().then(r => {
                });
                break;
            case "stopRecordAudio":
                this.stopRecordAudio().then(r => {
                })
                break
            case "uploadImage":
                this.uploadImage(obj.filePath);
                break;
            case "uploadFile":
                this.uploadFile(obj.filePath);
                break;
            case "markerImage":
                this.markerImage(obj);
                break;
            case "getDeviceInfo":
                this.getDeviceInfo();
                break;
            case "geolocation":
                this.getLocationInfo();
                break
            case "share":
                this.shareToFiles(obj).then(res => { });
                break
            case "AmapNavigation":
                let url = `androidamap://navi?sourceApplication=appname&poiname=fangheng&lat=36.547901&lon=104.258354&dev=1&style=2`;
                Linking.canOpenURL(url).then(supported => {
                    if (supported) {
                        Linking.openURL(url);
                    } else {
                        Alert.alert("请安装高德地图")
                    }
                })
                break
        }
    }

    //分享 ： 文件和 内容------------------------------------------------------


    shareToFiles = async (obj) => {
        const shareOptions = {
            title: '分享文件',
            failOnCancel: false,
            saveToFiles: true,
            urls: ["file:///" + obj.filePath], // base64 with mimeType or path to local file
        };
        try {
            const ShareResponse = await Share.open(shareOptions);
            return ShareResponse;
        } catch (error) {
            console.log('Error =>', error);
        }
    };



    // 设备信息 ------------------------------------------------------------------------------

    getDeviceInfo() {
        const device = {};
        device.DeviceBrand = DeviceInfo.getBrand();
        device.DeviceModel = DeviceInfo.getModel();
        device.SystemVersion = DeviceInfo.getSystemVersion();
        device.AppVersion = DeviceInfo.getVersion();
        device.AppReadableVersion = DeviceInfo.getReadableVersion();
        Promise.all([DeviceInfo.getAndroidId(), DeviceInfo.getUserAgent()]).then(res => {
            console.warn("===device=", res)
            device.DeviceID = res[0];
            device.UserAgent = res[1];
            let str = JSON.stringify(device);
            this.refs.webview.injectJavaScript(`deviceInfo('${str}');true;`);
        })
    }

    // 获取经纬度 位置信息 -------------------------------------------------------------------------


    getLocationInfo() {
        PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
            {
                title: '需要申请权限',
                message: '获取您当前的经纬度',
            });


        // gdGeo.getCurrentPosition((res) => {
        //     let data = JSON.stringify(res);
        //     console.warn('=位置信息1=', data);
        //     // this.refs.webview.injectJavaScript(`geolocation('${data}');true;`);
        // });

        // https://lbs.amap.com/api/webservice/guide/api/georegeo#scene
        geolocation.getCurrentPosition((location) => {
            this.setState({
                longitude: location.coords.longitude,//经度
                latitude: location.coords.latitude,//纬度
            });
            fetch(`https://restapi.amap.com/v3/assistant/coordinate/convert?locations=${this.state.longitude},${this.state.latitude}&coordsys=gps&output=json&key=144ed95a3743722dc69d4e54dd9d04e8`, { method: "GET" })
                .then(response => response.json())
                .then((jsonDa) => {

                    let newVar = jsonDa.locations.split(',')
                    this.setState({
                        longitude: newVar[0],//经度
                        latitude: newVar[1],//纬度
                    });
                    fetch('http://restapi.amap.com/v3/geocode/regeo?key=144ed95a3743722dc69d4e54dd9d04e8' + '&location=' + this.state.longitude + ',' + this.state.latitude + '&radius=200&extensions=all&batch=false&roadlevel=0', {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        },
                        body: ``
                    }).then((response) => response.json())
                        .then((jsonData) => {
                            console.warn("==经纬度=", jsonData.regeocode.formatted_address);
                            let str = JSON.stringify(jsonData);
                            this.refs.webview.injectJavaScript(`geolocation('${str}');true;`);

                            let text = jsonData.regeocode.formatted_address;
                            this.ttsAudio(text);

                        })
                        .catch((error) => {
                        });
                })
                .catch(error => {
                    reject(error);
                });
        }
        );
    }

    // 图片： 选择拍照 -上传 、打标记 ==============================================================================================================


    markerImage(obj) {
        Marker.markText({
            src: 'file://' + obj.filePath,
            text: '测试marker：\n' + obj.text,
            position: 'bottomLeft',
            color: '#FF0000',
            fontName: 'Arial-BoldItalicMT',
            fontSize: 30,
            scale: 1,
            quality: 100
        }).then((res) => {
            let filePath = AudioUtils.DownloadsDirectoryPath + '/marker.jpg';
            RNFS.copyFile(res, filePath).then(() => {
                this.refs.webview.injectJavaScript(`uploadFileSuccess(' ${filePath}');true;`);
            }, (error) => {
            });
        }).catch((err) => {
            console.warn("marker失败", err)
        })
    }
    takePhotos() {
        const options = {
            mediaType: 'video',
            includeBase64: false,
            maxHeight: 200,
            maxWidth: 200,
        };
        Imp.launchCamera(options, (res) => {
            let url = res.uri;
            if (url.startsWith('content://')) {
                const uriComponents = url.split('/')
                const fileNameAndExtension = uriComponents[uriComponents.length - 1]
                let destPath = AudioUtils.DownloadsDirectoryPath +"/"+fileNameAndExtension;
                RNFS.copyFile(url, destPath).then(() => {
                    this.refs.webview.injectJavaScript(`selectImageEvent("${destPath}");true;`);
                }, (error) => {
                    console.warn("=拷贝失败==", error)
                });
            }
        });




        // //接受到数据
        // const options = {
        //     title: '请选择',
        //     cancelButtonTitle: '取消',
        //     takePhotoButtonTitle: "拍摄照片",
        //     chooseFromLibraryButtonTitle: '选择相册',
        //     quality: 0.85,
        //     maxWidth: 1000,      // 加了这两句控制大小
        //     maxHeight: 1000,     // 加了这两句控制大小  
        //     allowsEditing: true,
        //     noData: false,
        //     storageOptions: {
        //         skipBackup: true,
        //         path: 'images'
        //     }
        // };

        // Imp.showImagePicker(options, (response) => {


        //     Alert.alert('======='+JSON.stringify(response) )

        //     if (response.didCancel) {

        //     } else if (response.error) {
        //         Alert.alert('错误啦' )
        //     } else if (response.customButton) {
        //         Alert.alert('自定义按钮:' + response.customButton)
        //     } else {
        //         Alert.alert( "选择数据","response.path： "+response.path)
        //         let path = response.path;
        //         this.refs.webview.injectJavaScript(`selectImageEvent("${path}");true;`);
        //         console.warn("=选择图片地址==", response)
        //     }
        // });




    }
    uploadImage(filePath) {
        let pathUrl = "file:///" + filePath;
        ImagePicker.openCropper({
            path: pathUrl
        }).then(image => {
            console.warn("=上传图片地址==", image.path)

            let formData = new FormData();
            let file = { uri: image.path, type: 'application/octet-stream', name: Date.now() + 'image.jpg' };
            formData.append("file", file);
            fetch("http://318z59f264.zicp.vip/test/uploadFile", {
                method: 'POST',
                headers: {
                    "Accept": 'application/json',
                    "Content-Type": "multipart/form-data"
                },
                body: formData,
            }).then((response) =>
                response.json()
            ).then((responseData) => {
                console.warn("=上传完成=", responseData)
                this.refs.webview.injectJavaScript(`uploadFileSuccess('https://www.baidu.com/img/PCfb_5bf082d29588c07f842ccde3f97243ea.png');true;`);
            }).catch((err) => {
                console.warn("=上传失败==", err)
            });

        }).catch(res => {
        });

        // fetch("http://192.168.137.214:8080/test/index", {
        //     method: 'GET',
        //     headers: {
        //         "Content-Type":"application/json"
        //     },
        // }).then((response) =>
        //     response.json()
        // ).then((responseData) => {
        //     console.warn("=上传完成=="+JSON.stringify(responseData))
        // }).catch((err) => {
        //     console.warn("=上传失败==",err)
        // });

    }


    //  录制视频 --------------------------------------------------------------------------------------------

    recordVideo() {



        imgp.getVideo({
            callback: (res) => {
                if (res.length <= 0) {
                    return
                }
                let videoUri = res[0].uri;
                let filePath = AudioUtils.DownloadsDirectoryPath + '/video.mp4';
                RNFS.copyFile(videoUri, filePath).then(() => {
                    this.refs.webview.injectJavaScript(`videoPath("${filePath}");true;`);
                }, (error) => {
                    console.warn("=拷贝失败==", error)
                });
            }
        })
    }
    uploadFile(filePath) {
        let pathUrl = "file://" + filePath;
        console.warn("=上传文件地址==", pathUrl)
        let formData = new FormData();
        let file = { uri: pathUrl, type: 'application/octet-stream', name: Date.now() + 'video.mp4' };
        formData.append("file", file);
        fetch("http://318z59f264.zicp.vip/test/uploadFile", {
            method: 'POST',
            headers: {
                "Accept": 'application/json',
                "Content-Type": "multipart/form-data"
            },
            body: formData,
        }).then((response) =>
            response.json()
        ).then((responseData) => {
            console.warn("=上传完成=", responseData)
        }).catch((err) => {
            console.warn("=上传失败==", err)
        });
    }

    // 音频相关   ----------------------------------------------------------------------------------------------------------------------------------------------------------


    //文字转语音
    ttsAudio(text) {
        let url = "https://tsn.baidu.com/text2audio";
        let params = {
            "tex": encodeURI(text),
            "tok": "24.47a59df68daf7e0b653d80fdc44498cf.2592000.1605685716.282335-22826809",
            "cuid": "baidu_workshop_huayun_tts",
            "ctp": "1",
            "lan": "zh"
        };
        let mp3Url = url + "?" + queryString.stringify(params);
        let mp3Uri = AudioUtils.DownloadsDirectoryPath + "/tts.mp3";
        RNFS.downloadFile({
            "fromUrl": mp3Url,
            "background": true,
            "toFile": mp3Uri
        }).promise.then(res => {
            if (res.statusCode == 200) {
                let music = new Sound(mp3Uri, '', (error) => {
                    if (error) {
                        return
                    }
                    music.play(success => {
                        if (success) {
                            console.warn('success - 播放成功')
                        } else {
                            console.warn('fail - 播放失败')
                        }
                    })
                })
            }
        }).catch(() => {
        })
    }



    //结束录音
    stopRecordAudio = async () => {
        try {
            await AudioRecorder.stopRecording();
        } catch (error) {
            console.error(error);
        }
    };

    //开始录制
    startRecordAudio = async () => {
        this.prepareRecordingPath(AudioUtils.DownloadsDirectoryPath + '/test.amr')
        try {
            await AudioRecorder.startRecording()
        } catch (err) {
            console.log(err)
        }

    };

    prepareRecordingPath = (path) => {
        const option = {
            SampleRate: 16000,            //采样率
            Channels: 1,                  //通道
            AudioQuality: "High",         //音质（Low, Medium, High）
            AudioEncoding: "amr_wb",         //音频编码（aac编码iOS和Android均支持）
            AudioEncodingBitRate: 48000,  //音频编码比特率
            OutputFormat: 'amr_wb',
            IncludeBase64: true,          //是否是base64格式
        }
        AudioRecorder.prepareRecordingAtPath(path, option)
    }

    audioEvent() {
        //录音监听
        AudioRecorder.requestAuthorization()
            .then(isAuthor => {
                console.log('是否授权: ' + isAuthor)
                if (!isAuthor) {
                    return alert('请前往设置开启录音权限')
                }
                AudioRecorder.onProgress = (data) => {  // 录音进展
                    console.warn("==录音时间回调=", Math.floor(data.currentTime))
                };
                // 完成录音
                AudioRecorder.onFinished = (data) => {
                    // data 返回需要上传到后台的录音数据
                    // console.warn("==录音结束=", data.audioFileURL)
                    // console.warn(data)
                    //转成wav格式上传到 百度api 识别 结果
                    // //转化
                    let pathUrl = data.audioFileURL.substr(7, data.audioFileURL.length);
                    //
                    RNFS.readFile(pathUrl, "base64")
                        .then((content) => {
                            RNFS.stat(pathUrl)
                                .then((StatResult) => {
                                    console.warn('=StatResult=', StatResult);
                                    this.uploadAudio(StatResult.size, content);
                                });
                        })
                };

            })
    }
    uploadAudio(audioSize, content) {
        let url = "https://vop.baidu.com/pro_api";
        let params = {
            "format": "amr",                    //语音文件的格式，pcm、wav、amr、m4a
            "rate": 16000,                      //采样率，16000，固定值
            "dev_pid": 80001,                   //普通话
            "channel": 1,                       //声道数，仅支持单声道，请填写固定值 1
            "token": "24.47a59df68daf7e0b653d80fdc44498cf.2592000.1605685716.282335-22826809",//开放平台获取到的开发者[access_token]
            "cuid": "baidu_workshop_huayun_semdo",            //用户唯一标识，用来区分用户，计算UV值。
            "len": audioSize,
            "speech": content,                   //本地语音文件的的二进制语音数据 ，需要进行base64 编码
        };
        console.log("content.length" + content.length)
        fetch(url, {
            method: 'POST',
            body: JSON.stringify(params),   //请求体
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            }
        })
            .then((response) => response.json())
            .then((data) => {
                if (data.err_no == 0) {
                    this.refs.webview.injectJavaScript(`speechRecognition('${data.result}');true;`);
                }
                console.warn("====识别结果==", data)
            })
            .catch((error) => {
                console.log('语音识别错误')
            });
    }
    loadError() {
    }
}
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F8FAFA',
        flex: 1
    }
});


